/**
 * Copyright (c) 2010 Claudio Imbrenda.
 * This program is released under the terms of the GNU GPL License, version 3 or later.
 */
 
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h> 

void usage(){
 fprintf(stderr,"usage: loadshmgraph inputfile shmhandle\n");
}

/** Loads given graph (in SHM format) into the given POSIX Shared Memory segment.
*/
int main(int argc, char*argv[]){
 int fd;
 FILE* inf;
 int i,tmp;
 
 if(argc<3){
  usage();
  exit(1);
 }
 
 /* create a new SHM segment with the given name */
 fd=shm_open(argv[2],O_RDWR|O_CREAT|O_EXCL,S_IRUSR|S_IWUSR);
 if(fd==-1) {
  fprintf(stderr,"Error opening SHM segment \"%s\".\n",argv[2]);
  goto fail;
 }
 
 /* open the input file, which must be already in the correct format */
 inf=fopen(argv[1],"r");
 if(inf==NULL){
  fprintf(stderr,"Error reading input file \"%s\".\n",argv[1]);
  goto fail;
 }
 
 /* copy the input file */
 i=fread(&tmp, sizeof(int), 1, inf);
 while(i!=0){
  if(write(fd,&tmp, sizeof(int))!=sizeof(int))goto fail;
  i=fread(&tmp, sizeof(int), 1, inf);
 }
 if(ferror(inf))goto fail;
 
 /* close the file descriptors */
 fclose(inf);
 close(fd);
 
 return 0;
fail:
 perror("error");
 return 1;
}

